package com.listen.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class IPProxyNew {
	//免费的
	private String url_free = "https://www.kuaidaili.com/free/inha/";
	private String url = "http://api3.xiguadaili.com/ip/?tid=555791453758662&num=50&longlife=20&filter=on";
	private String taiyang_url = "http://http.tiqu.qingjuhe.cn/getip?num=1&type=1&pro=&city=0&yys=0&port=1&pack=25557&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=0&regions=";
	private String url_n = "http://api3.xiguadaili.com/ip/?tid=555791453758662&category=2&longlife=20&filter=on";
	private static final String TESTURL = "http://119.29.22.54:8081/Login.aspx?ZY=1";
	//private String url_git = "http://api.ip.data5u.com/dynamic/get.html?order=d8308e3b2f42b4e2d2914a2dd061b3cb&sep=3";
	//private String url_niumo = "http://api.http.niumoip.com/v1/http/ip/get?p_id=136&s_id=2&u=DG8KaFZvXDgDMwAuB0lQb15xAj4AOAEQAVZUUAUD&number=1&port=1&type=2&map=1&pro=0&city=0&pb=1&mr=3&cs=1";
		
	public IPProxyNew(String url) {
		if(StringUtils.isNotBlank(url)) {
			this.taiyang_url = url;
		}
	}
	
	private IPProxyNew() {
	}
	
	private static List<String> list = null;
	RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(8000)  
			.setConnectTimeout(8000)  
			.setConnectionRequestTimeout(8000)
			.build();
	
	//获取代理IP
	public List<String> getIpAndPortList(){
		list = new ArrayList<String>();
		HttpGet httpGet = new HttpGet(url);
		String text = this.sendHttpGetStr(httpGet);
		String[] ips = text.split("\\r\\n");
		for(String ip :ips) {
			list.add(ip);
		}
		return list;
	}
	
	
	public String getOneIpAndPort(){
		HttpGet httpGet = new HttpGet(this.taiyang_url);
		String text = this.sendHttpGetStr(httpGet);
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(text);
		String ipAndPort = m.replaceAll("");
		try {
			Integer.parseInt(ipAndPort.split(":")[1]);
		} catch (Exception e) {
			return null;
		}
		return ipAndPort;
	}
	
	//获取代理IP
	public List<String> getIpAndPortFree(int n){
		list = new ArrayList<String>();
		url_free = url_free + n + "/";
		HttpGet httpGet = new HttpGet(url_free);
		String html = this.sendHttpGetStr(httpGet);
		Document document = Jsoup.parse(html);
		Element table = document.getElementById("list");
		Elements tbody = table.select("tbody");
		Elements trs = tbody.select("tr");
		for (int i = 0; i < trs.size(); ++i) {
	        // 获取一个tr  
			Element tr = trs.get(i);  
	        // 获取该行的所有td节点  
	        Elements tds = tr.select("td");
	        String ip = "";
	        String port = "";
	        String ipAndPort = "";
	        // 选择某一个td节点
	        for (int j = 0; j < tds.size(); ++j) {
	            Element td = tds.get(j); 
	            String val = td.attr("data-title");
	            if("IP".equalsIgnoreCase(val)){
	            	ip = td.text();
	            }
	            if("PORT".equalsIgnoreCase(val)){
	            	port = td.text();
	            	ipAndPort = ip +":"+port;
	            	if(!list.contains(ipAndPort)){
	    	        	list.add(ipAndPort);
	    	        }
	            	break;
	            }
	        }
	    }
		return list;
	}
	
	//获取指定个数代理IP
	public List<String> getIpAndPortList1(int n){
		list = new ArrayList<String>();
		url_n = url_n+"&num="+n;
		HttpGet httpGet = new HttpGet(url_n);
		String text = this.sendHttpGetStr(httpGet);
		if(text.startsWith("ERROR")) {
			int number = (int)(1+Math.random()*(10-1+1));
			list = getIpAndPortFree(number);
		}else {
			String[] ips = text.split("\\r\\n");
			for(String ip :ips) {
				list.add(ip);
			}
		}
		return list;
	}
	
	//获取指定个数代理IP
	public List<String> getTaiyangIpAndPortList(int n){
		list = new ArrayList<String>();
		this.taiyang_url = taiyang_url+"&num="+n;
		HttpGet httpGet = new HttpGet(taiyang_url);
		String text = this.sendHttpGetStr(httpGet);
		if(text.startsWith("ERROR")) {
			int number = (int)(1+Math.random()*(10-1+1));
			list = getIpAndPortFree(number);
		}else {
			String[] ips = text.split("\\r\\n");
			for(String ip :ips) {
				list.add(ip);
			}
		}
		return list;
	}
	//本机IP
	public String sendHttpGetStr(HttpGet httpGet) {
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;  
        String responseContent = null;  
        try {  
        	httpGet.setConfig(requestConfig);
            // 创建默认的httpClient实例.  
            httpClient = HttpClients.createDefault();  
            
            // 执行请求  
            response = httpClient.execute(httpGet);
            entity = response.getEntity();  
            responseContent = EntityUtils.toString(entity, "UTF-8");  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                // 关闭连接,释放资源  
                if (response != null) {  
                    response.close();  
                }  
                if (httpClient != null) {  
                    httpClient.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return responseContent;  
    }
	
	//获得一个可用的代理IP和端口
	public String getOneUseAbleProxyInfo(int n){
		HttpGet httpGet = new HttpGet(TESTURL);
		String proxy = null;
		try {
			for(int i=0;i<list.size();i++){
				proxy = list.get(i);
				boolean b = this.sendHttpGet(httpGet,list.get(i));
				//移除当前已使用过的IP
				list.remove(i);
				if(b) {
					break;
				}else{
					proxy = null;
				}
				//当剩余可用代理IP数小于2时，重新获取新的代理IP
				if(list.size() < 2){
					this.getIpAndPortList();
				}
			}
		} catch (Exception e) {
			System.out.println("遍历代理IP结果集异常--->"+e);
			e.printStackTrace();
		}
		return proxy;
	}
	
	//测试代理IP是否可用
	public boolean sendHttpGet(HttpGet httpGet,String proxyInfo) {
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;
        boolean b = false;
        try { 
    		String proxyIp = proxyInfo.split(":")[0];
    		int proxyPort = Integer.parseInt(proxyInfo.split(":")[1]);
    		HttpHost proxy = new HttpHost(proxyIp,proxyPort);
        	requestConfig = RequestConfig.custom().setProxy(proxy).build();
        	httpGet.setConfig(requestConfig);
        	// 创建默认的httpClient实例.  
            httpClient = HttpClients.createDefault();  
            // 执行请求  
            response = httpClient.execute(httpGet);
            int status = response.getStatusLine().getStatusCode();
            if(status == 200){
            	b = true;
            }
        } catch (Exception e) {  
        	b = false;
            e.printStackTrace();  
        } finally {  
            try {  
                // 关闭连接,释放资源  
                if (response != null) {  
                    response.close();  
                }  
                if (httpClient != null) {  
                    httpClient.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return b;  
    }
	
	public static void main(String args[]){
		IPProxyNew proxy = new IPProxyNew();
		/*proxy.getIpAndPortList(5);
		String ip = proxy.getOneUseAbleProxyInfo(1);
		HttpGet httpGet = new HttpGet(TESTURL);
		System.out.println("ip="+ip);
		System.out.println("test="+proxy.sendHttpGet(httpGet,ip));*/
		String ip = proxy.getOneIpAndPort();
		int port = Integer.parseInt(ip.split(":")[1]);
		System.out.println(ip.split(":")[0]);
		System.out.println(port);
	}
}
